package com.atguigu.lease.web.service.impl;

import com.atguigu.lease.exception.LeaseException;
import com.atguigu.lease.model.entity.*;
import com.atguigu.lease.model.enums.ItemType;
import com.atguigu.lease.model.enums.ReleaseStatus;
import com.atguigu.lease.result.ResultCodeEnum;
import com.atguigu.lease.web.mapper.*;
import com.atguigu.lease.web.service.*;
import com.atguigu.lease.web.vo.apartment.ApartmentDetailVo;
import com.atguigu.lease.web.vo.apartment.ApartmentItemVo;
import com.atguigu.lease.web.vo.apartment.ApartmentQueryVo;
import com.atguigu.lease.web.vo.apartment.ApartmentSubmitVo;
import com.atguigu.lease.web.vo.fee.FeeValueVo;
import com.atguigu.lease.web.vo.graph.GraphVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author liubo
 * @description 针对表【apartment_info(公寓信息表)】的数据库操作Service实现
 * @createDate 2023-07-24 15:48:00
 */
@Service
@Transactional
public class ApartmentInfoServiceImpl extends ServiceImpl<ApartmentInfoMapper, ApartmentInfo>
        implements ApartmentInfoService {

    @Autowired
    private GraphInfoMapper graphInfoMapper;
    @Autowired
    private GraphInfoService graphInfoService;
    @Autowired
    private ApartmentFacilityService apartmentFacilityService;
    @Autowired
    private ApartmentFeeValueService apartmentFeeValueService;
    @Autowired
    private ApartmentLabelService apartmentLabelService;

    @Autowired
    private ProvinceInfoService provinceInfoService;
    @Autowired
    private CityInfoService cityInfoService;
    @Autowired
    private DistrictInfoService districtInfoService;

    @Autowired
    private FacilityInfoMapper facilityInfoMapper;
    @Autowired
    private LabelInfoMapper labelInfoMapper;
    @Autowired
    private FeeValueMapper feeValueMapper;

    @Autowired
    private RoomInfoService roomInfoService;

    @Override
    public void customSaveOrUpdate(ApartmentSubmitVo apartmentSubmitVo) {
        // 判定是新增还是修改
        boolean isUpdate = apartmentSubmitVo.getId() != null;

        // 设置省 市 区 的名称
        apartmentSubmitVo.setProvinceName(provinceInfoService.getById(apartmentSubmitVo.getProvinceId()).getName());
        apartmentSubmitVo.setCityName(cityInfoService.getById(apartmentSubmitVo.getCityId()).getName());
        apartmentSubmitVo.setDistrictName(districtInfoService.getById(apartmentSubmitVo.getDistrictId()).getName());

        // 调用公寓的saveOrUpdate方法
        this.saveOrUpdate(apartmentSubmitVo);    // 多态
        // 如果是更新，删除关联表中的数据
        if (isUpdate) {
            // 图片表
            graphInfoMapper.delete(new LambdaQueryWrapper<GraphInfo>()
                    .eq(GraphInfo::getItemId, apartmentSubmitVo.getId())
                    .eq(GraphInfo::getItemType, ItemType.APARTMENT));
            // 配套中间表
            apartmentFacilityService.remove(new LambdaQueryWrapper<ApartmentFacility>()
                    .eq(ApartmentFacility::getApartmentId, apartmentSubmitVo.getId()));
            // 标签中间表
            apartmentLabelService.remove(new LambdaQueryWrapper<ApartmentLabel>()
                    .eq(ApartmentLabel::getApartmentId, apartmentSubmitVo.getId()));
            // 杂费中间表
            apartmentFeeValueService.remove(new LambdaQueryWrapper<ApartmentFeeValue>()
                    .eq(ApartmentFeeValue::getApartmentId, apartmentSubmitVo.getId()));
        }
        // 中间表数据批量保存
        // 图片信息
        if (!CollectionUtils.isEmpty(apartmentSubmitVo.getGraphVoList())) {
            List<GraphInfo> graphInfoList = apartmentSubmitVo.getGraphVoList().stream().map(item -> {
                GraphInfo graphInfo = new GraphInfo();
                graphInfo.setItemId(apartmentSubmitVo.getId());
                graphInfo.setItemType(ItemType.APARTMENT);
                graphInfo.setName(item.getName());
                graphInfo.setUrl(item.getUrl());
                return graphInfo;
            }).collect(Collectors.toList());
            graphInfoService.saveBatch(graphInfoList);
        }
        // 公寓配套
        if (!CollectionUtils.isEmpty(apartmentSubmitVo.getFacilityInfoIds())) {
            List<ApartmentFacility> apartmentFacilities = apartmentSubmitVo.getFacilityInfoIds().stream().map(item -> {
                return ApartmentFacility.builder().apartmentId(apartmentSubmitVo.getId()).facilityId(item).build();
            }).collect(Collectors.toList());
            apartmentFacilityService.saveBatch(apartmentFacilities);
        }
        // 公寓标签
        if (!CollectionUtils.isEmpty(apartmentSubmitVo.getLabelIds())) {
            List<ApartmentLabel> apartmentLabels = apartmentSubmitVo.getLabelIds().stream().map(item -> {
                return ApartmentLabel.builder().apartmentId(apartmentSubmitVo.getId()).labelId(item).build();
            }).collect(Collectors.toList());
            apartmentLabelService.saveBatch(apartmentLabels);
        }
        // 公寓杂费值
        if (!CollectionUtils.isEmpty(apartmentSubmitVo.getFeeValueIds())) {
            List<ApartmentFeeValue> apartmentFeeValues = apartmentSubmitVo.getFeeValueIds().stream().map(item -> {
                 return ApartmentFeeValue.builder().apartmentId(apartmentSubmitVo.getId()).feeValueId(item).build();
            }).collect(Collectors.toList());
            apartmentFeeValueService.saveBatch(apartmentFeeValues);
        }
    }

    @Override
    public void customPage(Page<ApartmentItemVo> page, ApartmentQueryVo queryVo) {
        baseMapper.customPage(page, queryVo);
    }

    @Override
    public ApartmentDetailVo getDetailById(Long id) {
        // 查询公寓基本信息
        ApartmentInfo apartmentInfo = this.getById(id);
        if (apartmentInfo == null) {
            return null;
        }
        // 查询配套详情(推荐直接调用配套的mapper)
        List<FacilityInfo> facilityInfoList = facilityInfoMapper.queryByApartmentId(id);
        // 查询图片
        List<GraphVo> graphInfoList = graphInfoMapper.queryByItemId(id, ItemType.APARTMENT);
        // 查询标签集合
        List<LabelInfo> labelInfoList = labelInfoMapper.queryByApartmentId(id);
        // 查询杂费和杂费名信息
        List<FeeValueVo> feeValueVoList = feeValueMapper.queryByApartmentId(id);
        // 合并对象并返回结果
        ApartmentDetailVo apartmentDetailVo = new ApartmentDetailVo();
        // 属性值迁移
        BeanUtils.copyProperties(apartmentInfo, apartmentDetailVo);
        apartmentDetailVo.setFacilityInfoList(facilityInfoList);
        apartmentDetailVo.setGraphVoList(graphInfoList);
        apartmentDetailVo.setLabelInfoList(labelInfoList);
        apartmentDetailVo.setFeeValueVoList(feeValueVoList);
        return apartmentDetailVo;
    }

    @Override
    public void customRemoveById(Long id) {
        // 判定公寓是否关联房间，如果有，则拒绝删除
        long count = roomInfoService.count(new LambdaQueryWrapper<RoomInfo>().eq(RoomInfo::getApartmentId, id));
        if (count > 0) {
            // 自定义各种类型异常
            throw new LeaseException(ResultCodeEnum.DELETE_ERROR.getMessage(), ResultCodeEnum.DELETE_ERROR.getCode());
        }
        // 删除跟公寓关联的数据 中间表, 避免存在孤儿数据
        this.removeById(id);
        // 图片
        graphInfoService.remove(new LambdaQueryWrapper<GraphInfo>().eq(GraphInfo::getItemId, id)
                .eq(GraphInfo::getItemType, ItemType.APARTMENT));
        // 标签
        apartmentLabelService.remove(new LambdaQueryWrapper<ApartmentLabel>().eq(ApartmentLabel::getApartmentId, id));
        // 杂费
        apartmentFeeValueService.remove(new LambdaQueryWrapper<ApartmentFeeValue>().eq(ApartmentFeeValue::getApartmentId, id));
        // 配套
        apartmentFacilityService.remove(new LambdaQueryWrapper<ApartmentFacility>().eq(ApartmentFacility::getApartmentId, id));
    }

    @Override
    public void updateReleaseStatusById(Long id, ReleaseStatus status) {
        // 方法一
        // ApartmentInfo apartmentInfo = new ApartmentInfo();
        // apartmentInfo.setId(id);
        // apartmentInfo.setIsRelease(status);
        // this.updateById(apartmentInfo);

        // 方法二
        // ApartmentInfo apartmentInfo = new ApartmentInfo();
        // apartmentInfo.setIsRelease(status);
        // this.update(apartmentInfo, new LambdaQueryWrapper<ApartmentInfo>().eq(ApartmentInfo::getId, id));

        // 方法三
        LambdaUpdateWrapper<ApartmentInfo> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(ApartmentInfo::getId, id);
        updateWrapper.set(ApartmentInfo::getIsRelease, status);
        this.update(updateWrapper);
    }
}




